<template>
	<section>
		<div style="padding:30px 0">
			<el-steps :active="step" finish-status="success" align-center center>
				<el-step title="选择分类"></el-step>
				<el-step title="填写信息"></el-step>
				<el-step title="上传图片"></el-step>
				<el-step title="发布成功"></el-step>
			</el-steps>
		</div>
		
		<div v-show="step==1" style="text-align:center;">
			<el-form :inline="false" :model="form">
				<el-form-item>
					<p>商城专区</p>
					<el-select v-model="form.type" clearable placeholder="商城专区" @change="typeChange">
						<el-option v-for="item,index in mallType" :label="item.name" :value="item.id" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<div class="block">
						<div>
							<el-cascader :options="goodsType" change-on-select placeholder="商品分类" v-model="categoryArr"
							             :props="goodsTypeProp" @change="handleChange">
							</el-cascader>
						</div>
						<el-button type="info" style="margin:20px auto;width:13.5%;" @click="step1">下一步</el-button>
					</div>
				</el-form-item>
			</el-form>
		</div>
		
		<div v-show="step==2">
			<el-form label-width="100px" ref="mainForm" :model="form" :rules="mainFormRules">
				<el-form-item label="商品分类">
					<el-col :span="6">
						<el-cascader :options="goodsType" change-on-select placeholder="商品分类" v-model="categoryArr"
						             :props="goodsTypeProp" @change="handleChange">
						</el-cascader>
					</el-col>
				</el-form-item>
				<el-form-item label="商品品牌" prop="brandId">
					<el-col :span="6">
						<el-select v-model="form.brandId" clearable placeholder="商品品牌">
							<el-option v-for="item,index in brandList" :label="item.name" :value="item.id" :key="index"></el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<el-form-item label="商品名称" prop="name">
					<el-col :span="8">
						<el-input v-model="form.name"></el-input>
					</el-col>
				</el-form-item>
				<div v-if="this.form.type == 3">
					<el-form-item label="商品标题" prop="title">
						<el-col :span="8">
							<el-input v-model="form.title"></el-input>
						</el-col>
					</el-form-item>
					
					<el-form-item label="旅游商品备注" prop="remark">
						<el-col :span="8">
							<el-input v-model="form.remark"></el-input>
						</el-col>
					</el-form-item>
					
					<el-form-item label="出发地" prop="firstPlace">
						<el-col :span="8">
							<el-input v-model="form.firstPlace"></el-input>
						</el-col>
					</el-form-item>
				</div>
				<el-form-item label="商品价格" prop="price">
					<div v-if="this.form.type == 1 || this.form.type == 3 || this.form.type == 4">
						<el-col :span="4">
							<el-input v-model.number="form.price">
								<template slot="append">元</template>
							</el-input>
						</el-col>
					</div>
					<div v-if="this.form.type == 2">
						<el-col :span="4">
							<el-input v-model.number="form.price">
								<template slot="append">积分</template>
							</el-input>
						</el-col>
					</div>
				</el-form-item>
				<el-form-item label="市场价" prop="marketPrice" v-if="this.obj.length <= 0">
					<el-col :span="3">
						<el-input v-model.number="form.marketPrice">
							<template slot="append">{{this.form.type == 2 ? '积分' : '元'}}</template>
						</el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="所属店铺" prop="roleId">
					<el-col :span="6">
						<el-select v-model="form.roleId" placeholder="请选择商城专区">
							<el-option v-for="item,index in shopList" :label="item.name" :value="item.id" :key="index"></el-option>
						</el-select>
					</el-col>
				</el-form-item>
				
				<!--SKU-->
				<div class="wrap" v-if="this.obj.length > 0">
					<div v-if="goodsId == '' || goodsId == undefined || goodsId == null">
						<div class="control-group choose_config">
							<el-form-item label="商品规格">
								<div class="controls">
									<div v-for="(item,index) in obj" :key="index">
										<h3 class="Father_Title">{{Object.keys(item).join()}}</h3>
										<ul :class="'Father_Item' + ' ' + 'Father_Item'+index">
											<li v-for="val,index in item[Object.keys(item).join()]" :key="index"><label><input
												id="Checkbox0" type="checkbox" @change="init"
												class="checkbox check_item" :value="val">{{val}}</label></li>
										</ul>
										<br>
									</div>
								</div>
							</el-form-item>
						</div>
						<!-- 生成表格 -->
						<div class="control-group mt10">
							<el-form-item>
								<div class="controls" id="createTable"></div>
							</el-form-item>
						</div>
					</div>
				</div>
				<!--SKU-->
				<!--回显库存表格-->
				<el-form-item label="库存信息"
				              v-if="(!goodsId == '' || !goodsId == undefined || !goodsId == null) && goodProucts.length > 0">
					<el-table :data="goodProucts">
						<el-table-column label="商品ID" prop="goodsId" align="center"></el-table-column>
						<el-table-column label="商品规格" prop="specs" align="center"></el-table-column>
						<el-table-column label="商品价格" prop="price" align="center"></el-table-column>
						<el-table-column label="市场价格" prop="marketPrice" align="center"></el-table-column>
						<el-table-column label="库存" prop="stock" align="center"></el-table-column>
						<el-table-column label="已售销量" prop="soldVolume" align="center"></el-table-column>
						<el-table-column label="库存预警值" prop="warnStock" align="center"></el-table-column>
						<el-table-column label="操作" align="center">
							<template slot-scope="scope">
								<el-button @click="editorKc(scope.$index, scope.row)">编辑</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<!--回显库存表格-->
				<el-form-item label="商品库存" prop="totalInventory" v-if="this.obj.length <= 0">
					<el-col :span="6">
						<el-input v-model.number="form.totalInventory" type="number"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="库存预警" prop="warnedInventory" v-if="this.obj.length <= 0">
					<el-col :span="4">
						<el-input v-model.number="form.warnedInventory" type="number"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="商品描述">
					<el-col :span="18">
						<myueditor id="content" ref="ueditor"></myueditor>
					</el-col>
				</el-form-item>
				<div v-show="this.form.type !== 4">
					<el-form-item label="限时特价">
						<el-col>
							<template>
								<el-radio class="radio" v-model="form.isSpecialPrice" :label="1">是</el-radio>
								<el-radio class="radio" v-model="form.isSpecialPrice" :label="0">否</el-radio>
							</template>
							<div v-show="form.isSpecialPrice==1">
								<el-row>
									<el-col :span="4">
										<el-form-item prop="specialPrice">
											<el-input v-model.number="form.specialPrice">
												<template slot="append">{{ this.form.type == 2 ? '积分' : '元' }}
												</template>
											</el-input>
										</el-form-item>
									</el-col>
									<el-col :span="4" :offset="1">
										<el-date-picker v-model="form.specialStartTime" format="yyyy-MM-dd HH:mm:ss"
										                type="datetime" placeholder="开始时间">
										</el-date-picker>
									</el-col>
									<el-col :span="4" :offset="1">
										<el-date-picker v-model="form.specialEndTime" format="yyyy-MM-dd HH:mm:ss"
										                type="datetime" placeholder="结束时间">
										</el-date-picker>
									</el-col>
								</el-row>
							</div>
						</el-col>
					</el-form-item>
					<el-form-item label="分销提成">
						<el-col>
							<template>
								<el-radio class="radio" v-model="form.isDistribution" :label="1">是</el-radio>
								<el-radio class="radio" v-model="form.isDistribution" :label="2">否</el-radio>
							</template>
							<div v-show="form.isDistribution==1">
								<el-row>
									<el-col :span="4" v-for="(item,k) in form.distributionSet" :key="k">
										<span>{{k+1}}级</span>
										<el-input v-model="form.distributionSet[k]" type="number">
											<template slot="append">%</template>
										</el-input>
									</el-col>
								</el-row>
							</div>
						</el-col>
					</el-form-item>
				</div>
				<el-form-item>
					<el-button type="info" style="margin:20px auto;width:50%;" @click="step2('mainForm')">下一步
					</el-button>
				</el-form-item>
			</el-form>
		
		</div>
		
		<div v-show="step==3">
			<el-form ref="form" label-width="80px">
				<el-form-item label="商品图片">
					<div v-for="item,index in this.tempPics" :key="index" style="float:left;position:relative;" @click="delPics(item)">
						<img :src="item" width="150" height="150" align="center"/>
					</div>
					<el-upload class="upload-demo" action="/file/upload"
					           name="file"
					           :data="fileType"
					           :on-success="onSuccessUpdate"
					           :on-error="onErrorUpdate"
					           multiple
					           :on-remove="handleRemove1"
					           list-type="picture-card"
					           :on-exceed="handleExceed"
					           :file-list="fileList"
					>
						<i class="el-icon-plus"></i>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				
				<!--<el-form-item label="图片成功地址" prop="img" v-show="false">
				  <el-input  v-model="form.img" auto-complete="off" placeholder="请输入url地址"></el-input>
				</el-form-item>-->
				
				<el-form-item>
					<el-button type="info" style="margin:20px auto;width:50%;" @click="step3">下一步</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="info" style="margin:20px auto;width:50%;" @click="step=2">返回</el-button>
				</el-form-item>
			</el-form>
		</div>
		
		<el-dialog title="修改库存信息" :visible.sync="dialogKc" size="tiny">
			<el-form :model="kcForm" ref="kcForm">
				<el-form-item label="商品价格" label-width="100px" prop="productPrice">
					<el-input v-model="kcForm.productPrice" placeholder="输入新的价格" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="库存" label-width="100px" prop="productStock">
					<el-input v-model.number="kcForm.productStock" placeholder="输入新的库存" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogKc = false">取 消</el-button>
				<el-button type="primary" @click="submitKc">确 定</el-button>
			</div>
		</el-dialog>
		
		<div v-show="step==4">
			发布成功
			<el-button type="info" style="margin:20px auto;width:50%;" @click="$router.push('/goods/list')">返回商品列表
			</el-button>
		
		</div>
	</section>
</template>

<script>
	import $ from '@/common/js/j'
	import {Loading} from 'element-ui';
	import myueditor from '../../components/UE.vue';
	import {
		goodsInfo,
		goodsCategoryList,
		categoryFeatureList,
		categoryFeatureValueList,
		brandList,
		goodsAdd,
		goodsUpdate,
		getAllGoodsCategory2,
		getShopList,
		getAllCategoryFeatureList,
		goodsSkuList,
		updateProduct
	} from '@/api/api';
	
	export default {
		components: {
			myueditor
		},
		data() {
			return {
				dialogKc: false,
				kcRow: null,
				kcForm: {
					productPrice: '',
					productStock: ''
				},
				goodsId: null,// 存储编辑iD
				goodProucts: [],// 回显sku列表
				tempPics: [],// step3图片编辑回显,
				_info: [],
				// sku
				count: 0,
				arr: [],
				goodArr: [],
				obj: {},
				form: {
					title: '',
					remark: '',
					firstPlace: '',
					attribute: '1',//规格属性初始
					brandId: '',
					name: "",
					priceType: 1,
					price: '',
					marketPrice: '',
					roleId: '',
					array1: [],
					totalInventory: '',//库存
					warnedInventory: '',//库存预警
					detail: '',
					isSpecialPrice: 0,
					specialStartTime: null,
					specialEndTime: null,
					specialPrice: 0,// 限时特价
					isDistribution: 2,
					distributionSet: [null, null],
					categoryId: '',// 商品分类ID
					type: '',// 商城类型
					imgArr: [],// 第三步图片数组
					
					
					pics: [],
					haveFeature: 0,
					selectedFeatures: {},
					featureImages: {},
					img: []
				},
				mallType: [
					{id: 1, name: "鸿福商城"},
					{id: 2, name: "积分商城"},
					{id: 3, name: "旅游专区"},
					{id: 4, name: "返利商城"},
				],
				categoryId: '',
				// 级联商品分类
				goodsType: [],
				goodsTypeProp: {
					value: 'id',
					label: 'name',
				},
				goods: [],
				mainFormRules: {
					brandId: [
						{required: true, message: '请输入商品牌', trigger: 'blur'},
					],
					name: [
						{required: true, message: '请输入商品名称', trigger: 'blur'},
					],
					roleId: [
						{required: true, message: '请输入所属店铺', trigger: 'blur'},
					],
					title: [
						{required: true, message: '请输入标题', trigger: 'blur'},
					],
					remark: [
						{required: true, message: '请输旅游备注', trigger: 'blur'},
					],
					firstPlace: [
						{required: true, message: '请输入出发地', trigger: 'blur'},
					],
					marketPrice: [
						{required: true, message: '不能为空'},
						{type: 'number', message: '必须为数字值'}
					],
					specialPrice: [
						/*{ required: true, message: '不能为空'},*/
						{type: 'number', message: '必须为数字值'}
					],
					price: [
						{required: true, message: '不能为空'},
						{type: 'number', message: '必须为数字值'}
					],
					totalInventory: [
						{required: true, message: '不能为空'},
						{type: 'number', message: '必须为数字值'}
					],
					warnedInventory: [
						{required: true, message: '不能为空'},
						{type: 'number', message: '必须为数字值'}
					],
					
				},
				featureUploadMethods: [],
				featureUploadFileList: [],
				uploadData: {
					"fileType": "SUMMARY_EVENT"
				},
				categoryArr: [],
				
				goodsImgs: [],
				step: 1,
				
				brandList: [],
				
				optionNameList: [],
				selectedType: [],
				selectedOption: [],
				goodsInventorys: [],
				featureList: [],
				goodsBonus: 2,
				startTime: "",
				endTime: "",
				shopList: [],//所属商城列表
				first: 0,//编辑 初始化数据
				
				fileType: {
					"fileType": "SUMMARY_EVENT"
				},
				fileList: [],
			};
		},
		methods: {
			//切换商城专区
			typeChange() {
				this.getAllCategory(this.form.type);
			},
			//切换商品分类
			handleChange() {
				if (this.categoryArr.length > 0) {
					this.form.categoryId = this.categoryArr[this.categoryArr.length - 1];
					let para = {
						categoryId: this.form.categoryId
					}
					goodsSkuList(para).then(res => {
						this.obj = res.data
					})
					if (!(this.first == 1 && this.form.haveFeature == 0)) {
						this.getGoodsFeature();
					}
				}
				;
			},
			
			// step2内容
			//获取商城专区下拉列表
			getGoodsShop() {
				let para = {};
				para.pageIndex = 1;
				para.pageSize = 1000;
				getShopList(para).then((res) => {
					this.shopList = res.data;
					this.shopList.map(v => {
						v.id = String(v.id)
					})
				});
			},
			//获取商品品牌
			getGoodsBrand() {
				let para = {
					pageIndex: 1,
					pageSize: 1000,
					startTime: null,
					endTime: null,
					keyword: null
				};
				brandList(para).then((res) => {
					this.brandList = res.data.data;
					this.brandList.map((v, i) => {
						v.id = String(v.id)
					})
				});
			},
			
			// 添加商品规格列表
			init() {
				$('.checkbox', parent).each(function () {
					var bCheck2 = true;
					if (_this.hasClass('check_all')) {
						if (_this.get(0).checked) {
							bCheck2 = true;
							$('.check_item', parent).prop('checked', bCheck2);
						} else {
							bCheck2 = false;
							$('.check_item', parent).prop('checked', bCheck2);
						}
						return false;
					} else {
						if ((!this.checked) && (!$(this).hasClass('check_all'))) {
							bCheck2 = false;
							$('.check_all', parent).prop('checked', bCheck2);
							return false;
						}
					}
					$('.check_all', parent).prop('checked', bCheck2);
				});
				this.Creat_Table();
			},
			Creat_Table() {
				this.hebingFunction();
				var SKUObj = $('.Father_Title');
				var arrayTile = new Array(); // 表格标题数组
				var arrayInfor = new Array(); // 盛放每组选中的CheckBox值的对象
				var arrayColumn = new Array(); // 指定列，用来合并哪些列
				var bCheck = true; // 是否全选，只有全选，表格才会生成
				var columnIndex = 0;
				$.each(SKUObj, function (i, item) {
					arrayColumn.push(columnIndex++);
					arrayTile.push(SKUObj.eq(i).text().replace('：', ''));
					var itemName = '.Father_Item' + i;
					var bCheck2 = true; // 是否全选
					
					// 获取选中的checkbox的值
					var order = new Array();
					$(itemName + ' .check_item:checked').each(function () {
						order.push($(this).val());
					});
					
					arrayInfor.push(order);
					if (order.join() == '') {
						bCheck = false;
					}
				})
				
				// 开始生成表格
				if (bCheck) {
					$('#createTable').html('');
					var table = $('<table id="process" class="columnList"></table>');
					table.appendTo($('#createTable'));
					var thead = $('<thead></thead>');
					thead.appendTo(table);
					var trHead = $('<tr></tr>');
					trHead.appendTo(thead);
					// 创建表头
					var str = '';
					$.each(arrayTile, function (index, item) {
						str += '<th width="100">' + item + '</th>';
					})
					str += '<th  width="">商品价格</th><th width="">市场价格</th><th width="">库存</th><th width="">已售销量</th><th width="">库存预警值</th>';
					
					trHead.append(str);
					var tbody = $('<tbody></tbody>');
					tbody.appendTo(table);
					var zuheDate = this.doExchange(arrayInfor);
					if (zuheDate.length > 0) {
						//创建行
						$.each(zuheDate, function (index, item) {
							var td_array = item.split(',');
							var tr = $('<tr></tr>');
							tr.appendTo(tbody);
							var str = '';
							$.each(td_array, function (i, values) {
								str += '<td>' + values + '</td>';
							});
							str += '<td ><input  value="" class="inpbox txt1 inpbox-mini" type="text"></td>';
							str += `<td ><input  value="" class="inpbox txt2 inpbox-mini" type="text"></td>`;
							str += '<td ><input  value="" class="inpbox txt3 inpbox-mini" type="text"></td>';
							str += '<td ><input  value="0" disabled="disabled" class="inpbox txt4 inpbox-mini" type="text"></td>';
							str += '<td ><input  value="" class="inpbox txt5 inpbox-mini" type="text"></td>';
							tr.append(str);
						});
					}
					
					//结束创建Table表
					arrayColumn.pop(); //删除数组中最后一项
					//合并单元格
					$(table).mergeCell({
						// 目前只有cols这么一个配置项, 用数组表示列的索引,从0开始
						cols: arrayColumn
					});
				} else {
					//未全选中,清除表格
					document.getElementById('createTable').innerHTML = "";
				}
			},
			hebingFunction: function () {
				$.fn.mergeCell = function (options) {
					return this.each(function () {
						var cols = options.cols;
						for (var i = cols.length - 1; cols[i] != undefined; i--) {
							mergeCell($(this), cols[i]);
						}
						dispose($(this));
					})
				};
				
				function mergeCell($table, colIndex) {
					$table.data('col-content', ''); // 存放单元格内容
					$table.data('col-rowspan', 1); // 存放计算的rowspan值 默认为1
					$table.data('col-td', $()); // 存放发现的第一个与前一行比较结果不同td(jQuery封装过的), 默认一个"空"的jquery对象
					$table.data('trNum', $('tbody tr', $table).length); // 要处理表格的总行数, 用于最后一行做特殊处理时进行判断之用
					// 进行"扫面"处理 关键是定位col-td, 和其对应的rowspan
					$('tbody tr', $table).each(function (index) {
						// td:eq中的colIndex即列索引
						var $td = $('td:eq(' + colIndex + ')', this);
						// 获取单元格的当前内容
						var currentContent = $td.html();
						// 第一次时走次分支
						if ($table.data('col-content') == '') {
							$table.data('col-content', currentContent);
							$table.data('col-td', $td);
						} else {
							// 上一行与当前行内容相同
							if ($table.data('col-content') == currentContent) {
								// 上一行与当前行内容相同则col-rowspan累加, 保存新值
								var rowspan = $table.data('col-rowspan') + 1;
								$table.data('col-rowspan', rowspan);
								// 值得注意的是 如果用了$td.remove()就会对其他列的处理造成影响
								$td.hide();
								// 最后一行的情况比较特殊一点
								// 比如最后2行 td中的内容是一样的, 那么到最后一行就应该把此时的col-td里保存的td设置rowspan
								// 最后一行不会向下判断是否有不同的内容
								if (++index == $table.data('trNum'))
									$table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
							}
							// 上一行与当前行内容不同
							else {
								// col-rowspan默认为1, 如果统计出的col-rowspan没有变化, 不处理
								if ($table.data('col-rowspan') != 1) {
									$table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
								}
								// 保存第一次出现不同内容的td, 和其内容, 重置col-rowspan
								$table.data('col-td', $td);
								$table.data('col-content', $td.html());
								$table.data('col-rowspan', 1);
							}
						}
					})
				}
				
				// 同样是个private函数 清理内存之用
				function dispose($table) {
					$table.removeData();
				}
			},
			doExchange: function (doubleArrays) {
				// 二维数组，最先两个数组组合成一个数组，与后边的数组组成新的数组，依次类推，知道二维数组变成以为数组，所有数据两两组合
				var len = doubleArrays.length;
				if (len >= 2) {
					var arr1 = doubleArrays[0];
					var arr2 = doubleArrays[1];
					var len1 = arr1.length;
					var len2 = arr2.length;
					var newLen = len1 * len2;
					var temp = new Array(newLen);
					var index = 0;
					for (var i = 0; i < len1; i++) {
						for (var j = 0; j < len2; j++) {
							temp[index++] = arr1[i] + ',' + arr2[j];
						}
					}
					var newArray = new Array(len - 1);
					newArray[0] = temp;
					if (len > 2) {
						var _count = 1;
						for (var i = 2; i < len; i++) {
							newArray[_count++] = doubleArrays[i];
						}
					}
					return this.doExchange(newArray);
				} else {
					this.form.array1 = doubleArrays[0]
					this.count = this.form.array1.length
					return doubleArrays[0];
				}
			},
			di() {
				this.goodArr = []
				for (let i = 0; i < $('.txt1').length; i++) {
					this.form.array1[i] += ',' + $('.txt1').eq(i).val()
					this.form.array1[i] += ',' + $('.txt2').eq(i).val()
					this.form.array1[i] += ',' + $('.txt3').eq(i).val()
					this.form.array1[i] += ',' + $('.txt4').eq(i).val()
					this.form.array1[i] += ',' + $('.txt5').eq(i).val()
				}
				
				for (let k = 0; k < this.form.array1.length; k++) {
					let obj2 = {};
					let str = this.form.array1[k].split(",");
					let strSize = str.length;
					let nameSize = this.obj.length;
					let o = this.obj
					if (strSize > 5) {
						for (let j = 0; j < nameSize; j++) {
							let first = Object.keys(o[j]).join()
							obj2[first] = str[j]
						}
						obj2.price = str[strSize - 5];
						obj2.marketPrice = str[strSize - 4];
						obj2.stock = str[strSize - 3];
						obj2.soldVolume = str[strSize - 2];
						obj2.warnStock = str[strSize - 1];
					}
					this.goodArr.push(obj2);
				}
				console.log(this.goodArr)
			},
			getContent() { //富文本内容
				return this.$refs.content.getUEContent();
			},
			//时间格式化
			dateFormat() {
				let date = new Date(Date.parse(date));
				let newDate = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-" + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
				return newDate;
			},
			formatDate(date, fmt) {
				if (/(y+)/.test(fmt)) {
					fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				let o = {
					'M+': date.getMonth() + 1,
					'd+': date.getDate(),
					'h+': date.getHours(),
					'm+': date.getMinutes(),
					's+': date.getSeconds()
				};
				for (let k in o) {
					if (new RegExp(`(${k})`).test(fmt)) {
						let str = o[k] + '';
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
					}
				}
				return fmt;
			},
			changeToDateStr(date) {
				return this.moment(date).format("YYYY-MM-DD HH:mm:ss");
			},
			uploadChange(file, fileList) {
				console.log(fileList);
				var imgs = [];
				this.form.pics = [];
				
				fileList.forEach((v, k) => {
					console.log(v)
					if (v.status == "success") {
						if (v.response.code == 20000) {
							this.form.pics.push(v.response.body);
							v.url = v.response.body;
						} else {
							this.$delete(fileList, k);
						}
					}
				})
				this.goodsImgs = fileList;
			},
			step1() {
				if (this.categoryArr.length > 0) {
					if (this.form.attribute == 0) {
						let para = {
							categoryId: this.form.categoryId
						}
						goodsSkuList(para).then(res => {
							this.obj = res.data
						})
					}
					this.step = 2;
				} else {
					this.$message({
						message: "请选择商品分类",
						type: 'error'
					});
				}
			},
			step2(mainForm) {
				this.$refs[mainForm].validate((valid) => {
					if (valid) {
						this.di();
						if (this.goodsId == null || this.goodsId == undefined || this.goodsId == '') {
							if (this.obj.length > 0) {
								if (this.goodArr.length <= 0) {
									this.$message({
										message: '警告哦，请填写完整库存信息',
										type: 'error'
									});
									return;
								}
							}
						}
						this.step = 3;
					} else {
						this.$message({
							message: '警告哦，请填写完整信息',
							type: 'error'
						});
					}
				});
			},
			step3() {
				let loadingInstance = Loading.service();
				var para = JSON.parse(JSON.stringify(this.form));
				para.detail = this.$refs.ueditor.getUEContent();
				if (this.obj.length > 0) {
					para.marketPrice = 0
				} else {
					para.marketPrice = this.form.marketPrice
				}
				para.goodsInventorys = JSON.parse(JSON.stringify(this.goodArr));
				para.haveFeature = para.goodsInventorys.length > 0 ? 1 : 0;
				para.distributionSet.forEach((v, k) => {
					para.distributionSet[k] = parseFloat(v);
				})
				var keys = Object.keys(para.selectedFeatures)
				keys.forEach((v) => {
					para.selectedFeatures[v].forEach((vv, kk) => {
						para.selectedFeatures[v][kk] = parseInt(vv);
					})
				})
				if (para.goodsInventorys != null && para.goodsInventorys != undefined) {
					var totalInventory = 0;
					var warnedInventory = 0;
					para.goodsInventorys = this.goodArr
					para.goodsProduct = JSON.stringify(this.goodArr);
					para.totalInventory = this.form.totalInventory;
					para.warnedInventory = this.form.warnedInventory;
				}
				para.specialStartTime = this.moment(this.form.specialStartTime).format();
				para.specialEndTime = this.moment(this.form.specialEndTime).format()
				if (this.goodsId == null) {
					goodsAdd(para).then(res => {
						loadingInstance.close();
						if (res.code == 0) {
							
							console.log(res);
							this.step = 4;
						} else {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						}
					})
				} else {
					let para = Object.assign(this.form)
					para.id = this.$route.query.id
					para.detail = this.$refs.ueditor.getUEContent();
					para.goodsProduct = JSON.stringify(this.goodArr);
					para.img = [...this.form.img, ...this.tempPics]
					this.shopList.map(v => {
						if (this.form.roleId == v.name) {
							para.roleId = v.id
						}
					})
					
					this.brandList.map(v => {
						if (v.name == this.form.brandId) {
							para.brandId = v.id
						}
					})
					
					goodsUpdate(para).then(res => {
						loadingInstance.close();
						if (res.code == 0) {
							console.log(res);
							this.step = 4;
						} else {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						}
					})
				}
				
			},
			onSuccessUpdate(response, file, fileList) {
				this.form.imgArr.push(file.response.body);
				//this.form.img = JSON.stringify(this.form.imgArr);//字符串数组
				this.form.img = this.form.imgArr
			},
			onErrorUpdate(response, file, fileList) {
				this.$message({
					showClose: true,
					message: '图片上传失败！',
					type: 'error'
				});
			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前超出限制！本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			// 删除图片
			delPics: function (value) {
				var index = this._info.goodsImages.indexOf(value);
				if (index > -1) {
					this._info.goodsImages.splice(index, 1);
				}
				;
				
				var tag = this.tempPics.indexOf(value);
				if (tag > -1) {
					this.tempPics.splice(index, 1);
				}
				;
			},
			handleRemove1(file, fileList) {
				this.delPics(file.response.body);
			},
			//根据商城分类获取所有商品分类
			getAllCategory(type) {
				let para = {type: type};
				getAllGoodsCategory2(para).then((res) => {
					console.log(res);
					if (res.code == 0) {
						this.goodsType = res.data.first;
						for (var i = 0; i < this.goodsType.length; i++) {
							this.goodsType[i].children = this.goodsType[i].second;
						}
						;
					}
					;
					if (this.first == 1) {
						for (var k in this.goodsType) {
							if (this.goodsType[k].id == this.form.categoryId) {
								this.$set(this.categoryArr, 0, this.goodsType[k].id);
								break;
							}
							for (var kk in this.goodsType[k]['children']) {
								if (this.goodsType[k]['children'][kk].id == this.form.categoryId) {
									
									this.$set(this.categoryArr, 0, this.goodsType[k].id);
									this.$set(this.categoryArr, 1, this.goodsType[k]['children'][kk].id);
									break;
								}
							}
						}
						this.handleChange();
					}
				});
			},
			
			//获取级联商品分类列表
			getGoodsFeature() {
				let para = {categoryId: this.form.categoryId};
				getAllCategoryFeatureList(para).then((res) => {
					if (res.code == 0) {
						this.featureList = res.data;
						if (this.first == 0 && this.form.selectedFeatures != undefined) {
							this.form.selectedFeatures = {};
						}
						this.selectedOption = [];
						this.featureList.forEach((v, k) => {
							if (this.first == 0 && this.form.selectedFeatures != undefined) {
								this.$set(this.form.selectedFeatures, v.id, []);
							}
							this.$set(this.featureList[k], "children", v.value);
							this.selectedOption.push({id: v.id, name: v.name, child: []});
						})
						if (this.first == 1) {
							var keys = Object.keys(this.form.selectedFeatures);
							this.selectedOption.forEach((v, k) => {
								if (keys.lastIndexOf(v.id) > -1) {
									var child = [];
									this.form.selectedFeatures[v.id].forEach((vv) => {
										var name = "";
										this.featureList.forEach((item) => {
											if (item.id == v.id) {
												item.children.forEach((child) => {
													if (child.id == vv) {
														name = child.name;
													}
												})
											}
										})
										child.push({id: vv, name: name});
									})
									this.$set(this.selectedOption[k], 'child', child);
								}
							})
							this.generateInventorySet();
						}
						
					}
				});
			},
			getGoodsFeatureItem(index, id) {
				let para = {featureId: id};
				var id1 = parseInt(Math.random() * 50);
				var id2 = parseInt(Math.random() * 50);
				var res = {data: [{id: id1, name: '选项' + id1}, {id: id2, name: '选项' + id2}]};
				this.$set(this.featureList[index], "children", res.data);
			},
			uploadBefore(file) {
				if (file.type.lastIndexOf("image") < 0) {
					this.$message({
						message: '请选择图片',
						type: 'warning'
					});
					return false;
				}
				return true;
			},
			generateInventorySet() {
				
				var t = this;
				
				var ids = [];
				var names = [];
				this.optionNameList = [];
				var selected = [];
				this.selectedOption.forEach((v, k) => {
					
					
					if (v.child.length > 0) {
						selected.push(v);
						this.optionNameList.push({name: v.name});
					}
				})
				if (selected.length < this.selectedOption.length) {
					
					this.goodsInventorys = [];
					return false;
				}
				var a = [];
				selected = selected.reduce(function (v1, v2) {
					var arr11 = [];
					if (v1 == null) {
						v2.child.forEach((vv, kk) => {
							arr11.push({features: [vv.id], feature_name: [vv.name]});
						})
					} else {
						v1.forEach((v, k) => {
							v2.child.forEach((vv, kk) => {
								arr11.push({
									features: v.features.concat(vv.id),
									feature_name: v.feature_name.concat(vv.name)
								});
							})
						})
					}
					return arr11;
				}, null);
				selected.forEach((v, k) => {
					var arr1 = v.features.slice(0);
					arr1.sort();
					selected[k]['features'] = JSON.stringify(v.features);
					if (t.first == 1) {
						var image_repeat = false;
						var keys = Object.keys(t.form.featureImages);
						if (keys.length > 0) {
							keys.forEach((key) => {
								var key_arr = [];
								var key_obj = JSON.parse(key);
								for (var key1 in  key_obj) {
									key_arr.push(key_obj[key1]);
								}
								key_arr.sort();
								if (arr1.equals(key_arr)) {
									image_repeat = true;
								}
							})
						}
						if (!image_repeat) {
							t.$set(t.form.featureImages, JSON.stringify(v.features), "");
						}
					}
					if (t.first == 1) {
						t.goodsInventorysTmp.forEach((vv, kk) => {
							var arr2 = JSON.parse(vv.features).slice(0);
							arr2.sort();
							if (arr1.equals(arr2)) {
								
								for (var kkk in vv) {
									selected[k][kkk] = vv[kkk];
								}
							}
						})
					} else {
						t.goodsInventorys.forEach((vv, kk) => {
							var arr2 = JSON.parse(vv.features).slice(0);
							arr2.sort();
							if (arr1.equals(arr2)) {
								
								for (var kkk in vv) {
									selected[k][kkk] = vv[kkk];
								}
							}
						})
					}
				})
				var methods = [];
				selected.forEach(function (v, k) {
					var func = (file, fileList) => {
						console.log("methods " + k);
						var item = null;
						fileList.forEach((vv, kk) => {
							if (vv.status == "success" && vv.response.code == 20000) {
								t.$set(t.form.featureImages, v.features, vv.response.body);
								item = vv;
							}
						})
						if (item != null) {
							t.featureUploadFileList[k] = [item];
						}
					};
					methods[k] = func;
				})
				this.featureUploadMethods = methods;
				this.goodsInventorys = selected;
				if (this.first == 1) {
					this.first = 0;
				}
			},
			// 编辑详情
			getDetail(id) {
				this.step = 2
				this.getGoodsBrand();
				this.categoryArr = [];
				this.getGoodsShop();
				this.tempPics = []
				goodsInfo({id: id}).then(res => {
					this.first = 1;
					var t = this;
					let data = Object.assign({}, res.data)
					let arr = []
					this._info = data
					if (this.tempPics.length > 0) {
						this.tempPics = JSON.parse(this.tempPics)
					}
					this.goodProucts = data.goodsProduct
					let arr2 = []
					data.goodsImages.map(v => {
						if (!v.image == '[]' || !v.image == '') {
							arr2.push(v.image)
						}
					})
					this.tempPics = arr2
					this.form.type = data.type
					this.brandList.map(v => {// 商品品牌回显name
						v.id = String(v.id)
						if (v.id == data.brandId) {
							this.form.brandId = v.name
						}
					})
					this.form.categoryId = data.categoryId
					this.form.attribute = data.haveFeature == 1 ? '1' : '0'
					this.form.name = data.name
					this.form.price = data.price
					this.form.marketPrice = data.marketPrice
					this.form.totalInventory = data.inventory
					this.form.warnedInventory = data.warnedInventory
					this.shopList.map(v => {
						v.id = String(v.id)
						if (v.id == data.shopId) {
							this.form.roleId = v.name
						}
					})
					setTimeout(function () {
						t.$refs.ueditor.setUEContent(data.detail);
					}, 500);
					this.form.isSpecialPrice = data.isSpecialPrice
					if (data.type == 3) {
						this.form.title = data.title
						this.form.remark = data.remark
						this.form.firstPlace = data.firstPlace
					}
					if (data.isSpecialPrice == 1) {
						this.form.specialPrice = data.specialPrice
						this.form.specialStartTime = data.specialStartTime
						this.form.specialEndTime = data.specialEndTime
					}
					this.form.isDistribution = data.openDistribution
					if (data.openDistribution == 1) {
						let arr = []
						arr.push(data.installOne)
						arr.push(data.installTwo)
						this.form.distributionSet = arr
					}
					
					if (data.pics != undefined) {
						data.pics.forEach((v) => {
							this.goodsImgs.push({url: v, response: {body: v, code: 20000}});
						})
					}
					if (this.form.selectedFeatures == undefined) {
						this.form.selectedFeatures = {};
					} else {
						var keys = Object.keys(this.form.selectedFeatures);
						keys.forEach((k) => {
							this.form.selectedFeatures[k].forEach((vv, kk) => {
								this.$set(this.form.selectedFeatures[k], kk, vv + "");
							})
						})
					}
					if (this.form.distributionSet == null || this.form.distributionSet == undefined || this.form.distributionSet.length == 0) {
						this.form.distributionSet = [null, null];
					}
					if (this.form.featureImages == undefined || this.form.featureImages == null) {
						this.$set(this.form, "featureImages", {});
					}
					
				})
			},
			editorKc(index, row) {
				this.kcRow = Object.assign({}, row)
				this.dialogKc = true
			},
			submitKc() {
				
				let para = {
					productId: this.kcRow.id,
					productPrice: this.kcForm.productPrice,
					productStock: this.kcForm.productStock,
				}
				updateProduct(para).then(res => {
					this.dialogKc = false
					goodsInfo({id: this.$route.query.id}).then(res => {
						let data = Object.assign({}, res.data)
						this.goodProucts = data.goodsProduct
						
					})
				})
			},
		},
		mounted() {
			let id = this.$route.query.id
			if (id != undefined) {
				this.getGoodsShop()
				this.goodsId = id;
				this.getDetail(id);
			} else {
				this.getGoodsBrand();
				this.getGoodsShop();
			}
		}
	}

</script>
<style lang="scss">
	.wrap {
		.hide {
			display: none;
		}
		.mt10 {
			margin-top: 10px;
		}
		.control-group {
			overflow: hidden;
		}
		.control-group a {
			color: #666;
			text-decoration: none;
		}
		.control-group a:hover {
			text-decoration: underline;
		}
		.control-label {
			float: left;
			width: 100px;
			line-height: 24px;
		}
		.controls {
			overflow: hidden;
		}
		.controls input[type="text"] {
			border: 1px solid #ddd;
			height: 20px;
			width: 120px;
		}
		.controls input[type="button"] {
			margin-top: 10px;
			height: 32px;
			cursor: pointer;
		}
		.config_item {
			margin-top: 10px;
			border: 1px dashed #ddd;
			padding: 10px;
		}
		.config_item section {
			margin-top: 10px;
		}
		.config_item section span {
			margin-right: 16px;
		}
		.config_item input[type="text"] {
			width: 80px;
			text-align: center;
		}
		.choose_config .Father_Title {
			margin: 0;
			margin-bottom: 10px;
			padding: 0;
			font-size: 16px;
			font-weight: normal;
			display: inline-block;
			vertical-align: middle;
		}
		.choose_config .Father_Item {
			padding: 0;
			margin: 0;
			margin-bottom: 10px;
			list-style: none;
			display: inline-block;
			vertical-align: middle;
		}
		.choose_config .Father_Item li {
			display: inline-block;
			margin-right: 10px;
		}
		.columnList {
			border-collapse: collapse;
		}
		.columnList th {
			background-color: #eee;
		}
		.columnList th, .columnList td {
			padding: 5px 10px;
			border: 1px solid #ddd;
			line-height: 24px;
			text-align: center;
		}
	}
	
	.el-upload--picture-card {
		position: relative;
	}
	
	.el-upload--picture-card span.pic_desc {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		color: white;
		padding: 15px 5px;
		line-height: 1;
	}
	
	.upload-hor {
		margin: 0 8px 8px 0;
		display: inline-block;
	}
	
	.upload-hor.is-success .el-upload--picture-card {
		border: none;
	}
	
	.upload-hor .el-icon-delete2 {
		color: white;
		font-size: 20px;
	}
	
	.upload-hor .el-upload-list__item-actions {
		display: none;
	}
	
	.upload-hor.is-success .el-upload-list__item-actions {
		display: block;
	}
</style>
